package com.example.springtest.course.service.impl;

import com.example.springtest.common.ServiceCode;
import com.example.springtest.common.ServiceException;
import com.example.springtest.course.mapper.CourseMapper;
import com.example.springtest.course.pojo.entity.Course;
import com.example.springtest.course.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 课程业务层
 */
@Service
@Transactional
public class CourseServiceImpl implements CourseService {
@Autowired
   private CourseMapper courseMapper;

    /**
     * 显示所有课程
     * @return
     */
    @Override
    public List<Course> getCourseList(){
        List<Course> courseList=courseMapper.getList();
        if(courseList==null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "不存在课程！");
        }
        return courseList;
    }

    /**
     * 新增课程
     * @param course
     */
    @Override
    public void addCourse(Course course){
        Course courses=new Course();
    courses.setCo_name(course.getCo_name());
    courses.setCo_major(course.getCo_major());
    courses.setStatus(course.getStatus());
    courses.setBook(course.getBook());
    int result=courseMapper.saveCourse(course);
    if(result!=1){
        throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"新增课程失败！");
    }
    }

    /**
     * 删减课程
     * @param id
     */
    @Override
    public void deleteCourse(Integer id){
        Course course=courseMapper.getByID(id);
        if(course==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该课程不存在！");
        }
        courseMapper.delete(id);
    }

    /**
     * 编辑课程
     * @param id
     * @param course
     */
    @Override
    public void editCourse(Integer id,Course course){
        Course course1=courseMapper.getByID(id);
        if(course1==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在该课程");
        }
        course1.setCo_name(course.getCo_name());
        course1.setCo_major(course.getCo_major());
        course1.setStatus(course.getStatus());
        course1.setBook(course.getBook());
        int result = courseMapper.edit(course1);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"更新失败！");
        }
    }
}
